//向服务器发送请求，获取文章分类数据
$.ajax({
    type:'get',
    url:'/categories',
    success:function(response){
        var html = template('categoryTpl',{data:response});
        console.log(response);
        $('#category').html(html);
    }
});

//当管理员选择文件时 触发事件
$('#feature').on('change',function(){
    var file = this.files[0];
    console.log(this.files);
    //创建二进制对象，实现文件上传
    var formData = new FormData();
    formData.append('cover',file);
    $.ajax({
        type:'post',
        url:'/upload',
        data:formData,
        processData:false,
        contentType:false,
        success:function(response){
            console.log(response);
            $('#thumbnail').val(response[0].cover);
        }
    });
});
//当添加文章表单提交时
$('#addForm').on('submit',function(){
    var formData = $(this).serialize();
    $.ajax({
        type:'post',
        url:'/posts',
        data:formData,
        success:function(){
            location.href='/admin/posts.html';
        }
    });
    return false;
})

var id = getUrlParams('id');
if(id!=-1){
    $.ajax({
        type:'get',
        url:'/posts/'+id,
        success:function(response){
            $.ajax({
                type:'get',
                url:'/categories',
                success:function(categories){
                    response.categories=categories;
                    console.log(response);
                    var html = template('modifyTpl',response)
                    $('#modifyBox').html(html);
                }
            });
           
        }
    })
}

//从浏览器获取查询参数
function getUrlParams(name){
    var paramsAry = location.search.substr(1).split('&');
    for(let i = 0;i<paramsAry.length;i++){
        var tem = paramsAry[i].split('=');
        if(tem[0]==name){
            return tem[1];
        }
    }
    return -1;
}

//使用委托事件提交修改后的文章
$('#modifyBox').on('submit','#modifyForm',function(){
    var formData = $(this).serialize();
    var id = $(this).attr('data-id');
    $.ajax({
        type:'put',
        url:'/posts/'+id,
        data:formData,
        success:function(){
            location.href = '/admin/posts.html';
        }
    });
    return false;
})